package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.servive.IUserService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.DBUtil;
import cn.wolfcode.shop.cloud.util.Md5Util;
import cn.wolfcode.shop.cloud.util.UserValidAnno;
import cn.wolfcode.shop.cloud.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private IUserService userService;

//    @RequestMapping("/get")
//    public User get(Long id) {
//        return userService.get(id);
//    }


    @RequestMapping("/doLogin")
    //用于验证注解是否符合要求，直接加在变量user之前，在变量中添加
    // 验证信息的要求，当不符合要求时就会在方法中返回message 的错误提示信息
    public Result doLogin(@Valid LoginVo loginVo, HttpServletResponse response) {
        //13088889999 111111
        String token = userService.doLogin(loginVo);
        //把Token以cookie的形式响应回给浏览器,设置在redis中过期时间,30分钟
        CookieUtil.addCookie("userToken", token, 1800, response);
        return Result.success(null);
    }
    //这个方法去redis中去取值key=前缀+token
    @RequestMapping("/getCurrent")
    //@CookieValue获取指定cookie的名字赋予变量token,required = false不带会报错,所以是false
//    public Result getCurrent(@CookieValue(name = "userToken", required = false) String token) {
//        return Result.success(userService.getCurrent(token));
//    }
    //使用了自定义的参数看解析器




    public Result getCurrent(@UserValidAnno User user) {
        //获取登录用户
        System.out.println(user);
        return Result.success(user);
    }


    @RequestMapping("/initData")
    @ResponseBody
    public Result<String> initData() throws Exception {
        List<User> users = initUser(500);
        insertToDb(users);
        createToken(users);
        return Result.success("");
    }

    private void createToken(List<User> users) throws Exception {
        File file = new File("D:/tokens.txt");
        if(file.exists()) {
            file.delete();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        file.createNewFile();
        raf.seek(0);
        for(int i=0;i<users.size();i++) {
            LoginVo vo = new LoginVo();
            vo.setUsername(users.get(i).getId()+"");
            vo.setPassword("111111");
            String token = userService.doLogin(vo);
            String row = users.get(i).getId()+","+token;
            raf.seek(raf.length());
            raf.write(row.getBytes());
            raf.write("\r\n".getBytes());
        }
        raf.close();
    }

    private void insertToDb(List<User> users) throws Exception {
        Connection conn = DBUtil.getConn();
        String sql = "insert into t_user(login_count, nickname, register_date, salt, password, id)values(?,?,?,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        for(int i=0;i<users.size();i++) {
            User user = users.get(i);
            pstmt.setInt(1, user.getLoginCount());
            pstmt.setString(2, user.getNickname());
            pstmt.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
            pstmt.setString(4, user.getSalt());
            pstmt.setString(5, user.getPassword());
            pstmt.setLong(6, user.getId());
            pstmt.addBatch();
        }
        pstmt.executeBatch();
        pstmt.close();
        conn.close();
    }
    //创建500个用户存储到集合中
    private List<User> initUser(int count){
        List<User> users = new ArrayList<>();
        for(int i=0;i<count;i++){
            User user = new User();
            user.setId(13000000000L+i);
            user.setLoginCount(1);
            user.setNickname("user"+i);
            user.setRegisterDate(new Date());
            user.setSalt("a64ed8");
            user.setPassword(Md5Util.endCode(user.getSalt(),"111111"));
            users.add(user);
        }
        return users;
    }


}
